package com.aifeng.fragment

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.aifeng.base.*
import com.aifeng.common_ui.base.*
import com.aifeng.common_ui.helper.formatDecimal
import com.aifeng.common_ui.helper.formatDecimalWhenHave
import com.aifeng.common_ui.helper.getString
import com.aifeng.common_ui.helper.isLogin
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.SearchActivity
import com.aifeng.hassan_food.login.LoginActivity
import com.aifeng.hassan_food.sale.DetailActivity
import com.aifeng.model.GoodsData
import com.aifeng.oss.scaleImage
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.subscribeByFinally
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.GoodsViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import kotlinx.android.synthetic.main.fragment_main_two.*
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import net.idik.lib.slimadapter.SlimAdapter
import org.koin.androidx.viewmodel.ext.android.getViewModel

class MainTwoFragment : BaseFragment() {

    private lateinit var mLeftAdapter: SlimAdapter
    private val mList = ArrayList<GoodsData>()
    private val mHeaderList = ArrayList<GoodsData>()
    private var mSelectId = ""

    //调用这个方法切换时不会释放掉Fragment
    override fun setMenuVisibility(menuVisible: Boolean) {
        super.setMenuVisibility(menuVisible)
        this.view?.visibility = if (menuVisible) View.VISIBLE else View.GONE
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.fragment_main_two, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initTitle()

        getTypeData()
    }

    override fun getViewModel() = getViewModel<GoodsViewModel>()

    @SuppressLint("SetTextI18n")
    override fun initTitle() {
        two_list.apply {
            loadLinear(getIContext())
            mLeftAdapter = SlimAdapter.create()
                .register<GoodsData>(R.layout.item_two_left) { inner, jector ->

                    val colorSelected = getIContext().getColorEx(R.color.colorAccent)
                    val colorNo = getIContext().getColorEx(R.color.gray)

                    jector.text(R.id.item_two_title, inner.typename)
                        .visibility(
                            R.id.item_two_back,
                            if (inner.isChecked) View.VISIBLE else View.INVISIBLE
                        )
                        .textColor(
                            R.id.item_two_title,
                            if (inner.isChecked) colorSelected else colorNo
                        )
                        .clicked(R.id.item_two_title) {
                            if (!inner.isChecked) {
                                mHeaderList.forEach { it.isChecked = false }
                                inner.isChecked = true
                                mLeftAdapter.notifyDataSetChanged()

                                mSelectId = inner.id
                            }

                            updateList()
                        }
                }
                .attachTo(this)
        }

        empty_hint.text = "暂无相关商品信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.loadLinear(getIContext(), swipe_refresh) {
            if (!isLoadingMore) {
                isLoadingMore = true
                getData(pageNum)
            }
        }

        mAdapter = SlimAdapter.create()
            .register<GoodsData>(R.layout.item_two_list) { data, injector ->

                val index = mList.indexOf(data)
                val isLast = index == mList.size - 1

                injector.text(R.id.item_two_name, data.goodname)
                    .text(
                        R.id.item_two_price,
                        setHtmlSmall(
                            "¥ ${if (getIContext().isLogin) data.price.formatDecimal() else data.orgprice.formatDecimal()}",
                            "¥"
                        )
                    )
                    .with<TextView>(R.id.item_two_orgin) {
                        it.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                        it.text = "¥ ${data.orgprice.formatDecimalWhenHave()}"
                    }
                    .with<ImageView>(R.id.item_two_img) {
                        val imgs = data.goodimg.split(",")
                        it.loadRoundedImage(url = imgs[0].scaleImage())
                    }
                    .visibility(
                        R.id.item_two_orgin,
                        if (getIContext().isLogin) View.VISIBLE else View.GONE
                    )
                    .visibility(
                        R.id.item_two_set,
                        if (data.specstype == "package") View.VISIBLE else View.GONE
                    )
                    .visibility(
                        R.id.item_two_divider2,
                        if (isLast) View.VISIBLE else View.GONE
                    )
                    .clicked(R.id.item_two_add) { view ->
                        if (getIContext().isLogin) {
                            getViewModel().addToCar(
                                data.id,
                                getString("userId"),
                                1
                            )
                                .bindLifeCycle(getLifecycleOwner())
                                .subscribeByNoError(
                                    event = getViewModel(),
                                    onSuccess = {
                                        val position = IntArray(2)
                                        view.getLocationInWindow(position)
                                        LiveEventBus.get("carList").post("refresh")
                                        LiveEventBus.get("updateNum")
                                            .post("${position[0]},${position[1]},$it")
                                    }
                                )
                        } else {
                            startActivityEx<LoginActivity>()
                        }
                    }
                    .clicked(R.id.item_two) {
                        startActivityEx<DetailActivity>("id" to data.id)
                    }
            }
            .attachTo(recycle_list)

        two_hint.oneClick { startActivityEx<SearchActivity>() }

        observe("mainLogin") { mAdapter.notifyDataSetChanged() }
    }

    private fun getTypeData() {
        getViewModel().getGoodsType()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mHeaderList.clear()
                    mHeaderList.add(GoodsData(typename = "全部", isChecked = true))
                    mHeaderList.addItems(it.goodsType)
                    mLeftAdapter.updateData(mHeaderList)
                },
                onFinally = {
                    mSelectId = ""
                    updateList()
                }
            )
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().getGoodsList(
            page = index,
            id = mSelectId
        )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mList.apply {
                        if (index == 1) {
                            clear()
                            pageNum = index
                        }
                        addItems(it)
                        if (count(it) > 0) pageNum++
                    }

                    mAdapter.updateData(mList)
                },
                onFinally = {
                    swipe_refresh.isRefreshing = false
                    isLoadingMore = false
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                }
            )
    }

    private fun updateList() {
        swipe_refresh.isRefreshing = true

        empty_view.gone()
        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        pageNum = 1
        getData(pageNum)
    }

}
